﻿using System;
using System.Windows.Forms;
using SGLL.Properties;

namespace SGLL
{
    public partial class FormCalls : FormTemplate
    {
        //Global Variables
        private string[] _doctor;
        private string _callID;
        //Class Constructor
        public FormCalls()
        {
            InitializeComponent();
        }
        //Form
        private void FormCalls_Load(object sender, EventArgs e)
        {
            try
            {
                //Variables
                _doctor = new string[2];
                //Fill out ComboBoxes
                tableAdapterRoute.Fill(dataSetCalls.PROCEDURE_ROUTE_CONSULTATION);
                tableAdapterUsers.Fill(dataSetCalls.PROCEDURE_USERS_CONSULTATION);
                tableAdapterCloseByUsersFilterSpecial.Fill(dataSetCalls.PROCEDURE_USERS_CONSULTATION_SPECIAL);
                //Setting up the Form
                toolStripButtonClear_Click(null, null);
                //ComboBoxes
                comboBoxRouteFilter.SelectedIndex = comboBoxOpenByUserFilter.SelectedIndex = comboBoxCloseByUserFilter.SelectedIndex = -1;
                //ToolTip Text
                toolTipCalls.Active = Settings.Default.ShowToolTips;
                //Functions
                RefreshCalls();
            }
            catch (Exception exception)
            {
                ClassFunctions.ErrorLog(exception);
                Close();
            }
        }
        //Label
        private void labelDoctorValue_TextChanged(object sender, EventArgs e)
        {
            EnableButtonSave();
        }
        //Text Boxes
        private void textBoxComments_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = !ClassFunctions.TextInputFilter(ClassFunctions.Filters.Alphanumeric, e.KeyChar);
        }
        //CheckBoxes
        private void checkBoxRequets_CheckedChanged(object sender, EventArgs e)
        {
            EnableButtonSave();
        }
        //Buttons
        private void buttonDoctor_Click(object sender, EventArgs e)
        {
            try
            {
                _doctor = new ClassConsultation("Consulta de Doctores", ClassSQL.GetDoctors).Show();
                labelDoctorValue.Text = _doctor[1];
                checkBoxEmail.Enabled = !string.IsNullOrWhiteSpace(_doctor[2]);
            }
            catch (Exception exception)
            {
                ClassFunctions.ErrorLog(exception);
            }
        }
        //Tool Strip Buttons
        protected override void toolStripButtonSave_Click(object sender, EventArgs e)
        {
            try
            {
                toolStripButtonSave.Enabled = false;
                ClassFunctions.SetData(ClassSQL.SetUpDateCalls, new[] { _callID, textBoxComments.Text.Trim(), comboBoxOpenByUser.Text, checkBoxSample.Checked.ToString(), checkBoxShipping.Checked.ToString(), checkBoxResult.Checked.ToString(), checkBoxVials.Checked.ToString(), checkBoxPromotional.Checked.ToString(), checkBoxPrices.Checked.ToString(), checkBoxVisit.Checked.ToString(), _doctor[0], string.IsNullOrEmpty(comboBoxCloseByUser.Text) ? null : comboBoxCloseByUser.Text });
                if (_callID.Equals("0") && checkBoxEmail.Checked) ClassFunctions.SendMail(_doctor[2], string.Format("[SGLL] Número de Orden {0}", labelIDValue.Text), string.Format("Correo Electrónico de Confirmación{0}Número de Orden: {1}", Environment.NewLine, labelIDValue.Text));
                toolStripButtonClear_Click(null, null);
                RefreshCalls();
            }
            catch (Exception exception)
            {
                ClassFunctions.ErrorLog(exception);
            }
        }
        protected override void toolStripButtonPrint_Click(object sender, EventArgs e)
        {
            try
            {
                if (!toolStripButtonPrint.Enabled) return;
                FormPrintPreview formPrintPreview = new FormPrintPreview
                (
                    dateTimePickerDate.Checked ? dateTimePickerDate.Value : Convert.ToDateTime("1-1-1 0:0:0.0"),
                    comboBoxRouteFilter.SelectedValue == null ? null : comboBoxRouteFilter.Text,
                    comboBoxOpenByUserFilter.SelectedValue == null ? null : comboBoxOpenByUserFilter.Text,
                    comboBoxCloseByUserFilter.SelectedValue == null ? null : comboBoxCloseByUserFilter.Text,
                    comboBoxRequestsFilter.SelectedIndex.Equals(0),
                    comboBoxRequestsFilter.SelectedIndex.Equals(1),
                    comboBoxRequestsFilter.SelectedIndex.Equals(2),
                    comboBoxRequestsFilter.SelectedIndex.Equals(3),
                    comboBoxRequestsFilter.SelectedIndex.Equals(4),
                    comboBoxRequestsFilter.SelectedIndex.Equals(5),
                    comboBoxRequestsFilter.SelectedIndex.Equals(6)
                ) { MdiParent = this.MdiParent, WindowState = FormWindowState.Maximized };
                formPrintPreview.Show();
            }
            catch (Exception exception)
            {
                ClassFunctions.ErrorLog(exception);
                this.Close();
            }
        }
        protected override void toolStripButtonClear_Click(object sender, EventArgs e)
        {
            try
            {
                //Variables
                _doctor = new string[3];
                _callID = "0";
                //Label
                labelDoctorValue.Text = labelDateTimeValue.Text = string.Empty;
                labelIDValue.Text = ClassFunctions.GetSingleData(string.Format(ClassSQL.GetNextID, "[CALLS]")).ToString();
                //TextBoxes
                textBoxComments.Text = string.Empty;
                //ComboBoxes
                comboBoxCloseByUser.SelectedIndex = -1;
                //CheckBoxes
                checkBoxSample.Checked = checkBoxShipping.Checked = checkBoxResult.Checked = checkBoxVials.Checked = checkBoxPromotional.Checked = checkBoxPrices.Checked = checkBoxVisit.Checked = checkBoxEmail.Checked = false;
                //Tool Strip Status
                ((FormMain)this.MdiParent).toolStripStatusLabelCallsValue.Text = ClassFunctions.GetTotalCalls();
                ((FormMain)this.MdiParent).toolStripStatusLabelLastCallValue.Text = ClassFunctions.GetLastCall();
                //Functions
                EnabledControls(true);
                //Focus
                buttonDoctor.Focus();
            }
            catch (Exception exception)
            {
                ClassFunctions.ErrorLog(exception);
            }
        }
        protected override void toolStripButtonCancel_Click(object sender, EventArgs e)
        {
            FormMain formMain = (FormMain)this.ParentForm;
            formMain.toolStripMenuItemCall.Enabled = true;
            Close();
        }
        //ComboBoxes
        private void comboBoxes_KeyDown(object sender, KeyEventArgs e)
        {
            if (!e.KeyCode.Equals(Keys.Delete)) return;
            ComboBox comboBox = sender as ComboBox;
            comboBox.SelectedIndex = -1;
            EnableButtonSave();
        }
        private void comboBoxes_SelectionChangeCommitted(object sender, EventArgs e)
        {
            EnableButtonSave();
        }
        private void comboBoxFilters_KeyDown(object sender, KeyEventArgs e)
        {
            if (!e.KeyCode.Equals(Keys.Delete)) return;
            ComboBox comboBox = sender as ComboBox;
            comboBox.SelectedIndex = -1;
            RefreshCalls();
        }
        private void comboBoxFilters_SelectionChangeCommitted(object sender, EventArgs e)
        {
            RefreshCalls();
        }
        //DateTimePicker
        private void dateTimePickerDate_ValueChanged(object sender, EventArgs e)
        {
            RefreshCalls();
        }
        //Data Grid View
        private void dataGridViewCalls_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            //Validation
            if (dataGridViewCalls.CurrentRow == null) return;
            //Coding
            _callID = labelIDValue.Text = dataGridViewCalls[0, e.RowIndex].Value.ToString();
            comboBoxOpenByUser.Text = dataGridViewCalls[2, e.RowIndex].Value.ToString();
            _doctor[0] = labelDoctorValue.Text = dataGridViewCalls[3, e.RowIndex].Value.ToString();
            checkBoxSample.Checked = Convert.ToBoolean(dataGridViewCalls[4, e.RowIndex].Value);
            checkBoxShipping.Checked = Convert.ToBoolean(dataGridViewCalls[5, e.RowIndex].Value);
            checkBoxResult.Checked = Convert.ToBoolean(dataGridViewCalls[6, e.RowIndex].Value);
            checkBoxVials.Checked = Convert.ToBoolean(dataGridViewCalls[7, e.RowIndex].Value);
            checkBoxPromotional.Checked = Convert.ToBoolean(dataGridViewCalls[8, e.RowIndex].Value);
            checkBoxPrices.Checked = Convert.ToBoolean(dataGridViewCalls[9, e.RowIndex].Value);
            checkBoxVisit.Checked = Convert.ToBoolean(dataGridViewCalls[10, e.RowIndex].Value);
            labelDateTimeValue.Text = string.Format("{0}/{1}/{2} {3}", dataGridViewCalls[0, e.RowIndex].Value.ToString().Substring(6, 2), dataGridViewCalls[0, e.RowIndex].Value.ToString().Substring(4, 2), dataGridViewCalls[0, e.RowIndex].Value.ToString().Substring(0, 4), dataGridViewCalls[1, e.RowIndex].Value);
            textBoxComments.Text = dataGridViewCalls[13, e.RowIndex].Value.ToString();
            //Check if the calls is still open
            if (Convert.ToBoolean(ClassFunctions.GetSingleData(string.Format(ClassSQL.IsCallOpen, dataGridViewCalls[0, e.RowIndex].Value))))
                comboBoxCloseByUser.SelectedIndex = -1;
            else
                comboBoxCloseByUser.Text = dataGridViewCalls[14, e.RowIndex].Value.ToString();

            EnabledControls(false);
            EnableButtonSave();
        }
        //General Purpose-Functions
        private void EnableButtonSave()
        {
            toolStripButtonSave.Enabled = 
                !comboBoxOpenByUser.SelectedIndex.Equals(-1) &&
                (checkBoxSample.Checked || checkBoxShipping.Checked || checkBoxResult.Checked || checkBoxVials.Checked || checkBoxPromotional.Checked || checkBoxPrices.Checked || checkBoxVisit.Checked) && 
                !string.IsNullOrEmpty(labelDoctorValue.Text);
        }
        private void EnabledControls(bool value)
        {
            labelID.Enabled =
                labelOpenByUser.Enabled =
                comboBoxOpenByUser.Enabled =
                labelDoctor.Enabled =
                buttonDoctor.Enabled =
                labelRequests.Enabled =
                tableLayoutPanelRequests.Enabled =
                labelDateTime.Enabled =
                labelEmail.Enabled =
                checkBoxEmail.Enabled = value;
            //Setting comments and closing user
            labelComments.Enabled =
            textBoxComments.Enabled =
            comboBoxCloseByUser.Enabled = comboBoxCloseByUser.SelectedIndex.Equals(-1);
        }
        private void RefreshCalls()
        {
            try
            {
                //Prevent unwanted automatic selection
                dataGridViewCalls.RowEnter -= dataGridViewCalls_RowEnter;
                //Fill Grid with data & Set up Group Box
                groupBoxCalls.Text = string.Format(Resources.groupBoxCalls,
                    tableAdapterCalls.Fill(
                        dataSetCalls.PROCEDURE_CALLS_CONSULTATION,
                        dateTimePickerDate.Checked ? dateTimePickerDate.Value : Convert.ToDateTime(Settings.Default.NullDate),
                        comboBoxRouteFilter.SelectedValue == null ? null : comboBoxRouteFilter.Text,
                        comboBoxOpenByUserFilter.SelectedValue == null ? null : comboBoxOpenByUserFilter.Text,
                        comboBoxCloseByUserFilter.SelectedValue == null ? null : comboBoxCloseByUserFilter.Text,
                        comboBoxRequestsFilter.SelectedIndex.Equals(0),
                        comboBoxRequestsFilter.SelectedIndex.Equals(1),
                        comboBoxRequestsFilter.SelectedIndex.Equals(2),
                        comboBoxRequestsFilter.SelectedIndex.Equals(3),
                        comboBoxRequestsFilter.SelectedIndex.Equals(4),
                        comboBoxRequestsFilter.SelectedIndex.Equals(5),
                        comboBoxRequestsFilter.SelectedIndex.Equals(6)
                    ));
                //Clear Selection
                dataGridViewCalls.ClearSelection();
                //Enabled Buttons
                toolStripButtonPrint.Enabled = !dataGridViewCalls.Rows.Count.Equals(0);
                //Restore Method
                dataGridViewCalls.RowEnter += dataGridViewCalls_RowEnter;
            }
            catch (Exception exception)
            {
                ClassFunctions.ErrorLog(exception);
            }
        }
    }
}